import 'package:flutter_taotaoshipin/generated/json/base/json_convert_content.dart';
import 'package:flutter_taotaoshipin/http/dao/user_dao.dart';
import 'package:flutter_taotaoshipin/value/constant.dart';

class BaseEntity<T> {
  BaseEntity(this.code, this.message, this.data, this.redirect);

  BaseEntity.fromJson(Map<String, dynamic> json) {
    code = json[Constant.code] as int?;
    message = json[Constant.message] as String;
    if (json.containsKey(Constant.data)) {
      data = _generateOBJ<T>(json[Constant.data] as Object?);
      dataAll = json[Constant.data];
    }
    redirect = json[Constant.redirect] as String;

    // code = 11 调用登录页面
    if (code == 11) {
      // Get.offAllNamed(LoginRoutes.phoneLogin, arguments: {'type': 1});
      UserDao.refreshLogin();
    }
  }

  int? code;
  late String message;
  T? data;
  String? redirect;
  dynamic dataAll;

  T? _generateOBJ<O>(Object? json) {
    if (json == null) {
      return null;
    }
    if (T.toString() == 'String') {
      return json.toString() as T;
    } else if (T.toString().startsWith('Map<')) {
      return json as T;
    } else if (T.toString().startsWith('List<')) {
      var map = json as Map;
      return JsonConvert.fromJsonAsT<T>(map['List'] ?? map['list']);
    } else {
      /// List类型数据由fromJsonAsT判断处理
      return JsonConvert.fromJsonAsT<T>(json);
    }
  }
}
